package com.mtiiot.fsmanage.controller;

import com.mtiiot.fscore.bean.DfsFileInfo;
import com.mtiiot.fscore.bean.MetadataInfo;
import com.mtiiot.fscore.inter1.FastdfsService1;
import com.mtiiot.fsmanage.server.NettyServer;
import com.mtiiot.fsmanage.utils.FileUtil;
import com.mtiiot.fsmanage.utils.FsViewConfig;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by xyr on 2016/8/24.
 * netty 文件查询服务
 */

@SuppressWarnings("all")
@Controller
public class NettyController {

    @Autowired
    NettyServer nettyServer;
    @Autowired
    private FsViewConfig fsViewConfig;
    @Autowired
    private FastdfsService1 fastdfsService1;

    /**
     * 查询netty存分布式文件系统的元数据
     *
     * @return
     */
    @RequestMapping(value = "/netty/nettyQuery.action", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Object nettyQuery(String sysName, String deviceId, String code, String times, String queryKeyWord, int count) throws Exception {
        Object obj = nettyServer.nettyQuery(sysName, deviceId, code, times, queryKeyWord, count);
        ObjectMapper mapper = new ObjectMapper();
        String jsonStr = mapper.writeValueAsString(obj);
        return jsonStr;
    }

    /**
     * 获得netty的树
     */
    @RequestMapping(value = "/netty/getNettyChildrenNode.action", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Object getNettyChildrenNode(String id, String deviceId) throws Exception {
        Object obj = nettyServer.getNettyChildrenNode(id, deviceId);
        ObjectMapper mapper = new ObjectMapper();
        String jsonStr = mapper.writeValueAsString(obj);
        return jsonStr;
    }

    /**
     * 根据id获得分布式文件系统的文件内容
     */
    @RequestMapping(value = "/netty/getFileContentById.action", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Object getFileContentById(String dfsId, String code) throws Exception {
        Object obj = nettyServer.getFileContentById(dfsId, code);
        ObjectMapper mapper = new ObjectMapper();
        String jsonStr = mapper.writeValueAsString(obj);
        return jsonStr;
    }

    /**
     * 批量重传数据
     */
    @RequestMapping(value = "/netty/uploadNettyFiles.action", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Object uploadNettyFiles(String nettyFilesJson) throws Exception {
        Object obj = nettyServer.uploadNettyFiles(nettyFilesJson);
        ObjectMapper mapper = new ObjectMapper();
        String jsonStr = mapper.writeValueAsString(obj);
        return jsonStr;
    }

    /**
     * 单个下载文件
     */
    @RequestMapping(value = "/netty/downloadNettyFile.action")
    @ResponseBody
    public void downloadFile(String dfsId, String ext, String code, String deviceId,String seqNo, HttpServletResponse response) {
        InputStream in = null;
        ServletOutputStream out = null;
        try {
            byte[] data = fastdfsService1.getFile(new MetadataInfo(fsViewConfig.getFsviewSysId()), dfsId).getFile();
            String times = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
            String fileName = "["+code+"]-"+deviceId+"-"+times+"_"+seqNo+"."+ext;
            response.setContentType("application/x-download");
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            out = response.getOutputStream();
            in = new ByteArrayInputStream(data);
            IOUtils.copy(in, out);
            out.flush();
        } catch (Exception e) {
            in = null;
            out = null;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    /**
     * 批量下载文件
     */
    @RequestMapping(value = "/netty/downloadNettyFiles.action")
    @ResponseBody
    public void downloadFiles(String content, HttpServletResponse response) {
        InputStream in = null;
        ServletOutputStream out = null;
        String Id = "group1/M00/1D/41/CnXXwVe7uHSAIiWhAABELa0_rJs97.docx@docx,group1/M00/1D/41/CnXXwVe7uHSAIiWhAABELa0_rJs97.docx@docx,";
        List<File> list = new ArrayList<File>();
        String zipFileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())+ ".zip";
        File zipFile = new File(zipFileName);
        try {
            JSONArray jsonArray = JSONArray.fromObject(content);
            int len = jsonArray.size();
            for (int i =0; i < len; i++){
                JSONObject jsonObject = JSONObject.fromObject(jsonArray.get(i));
                String dfsId = jsonObject.getString("dfsId");
                if (StringUtils.isBlank(dfsId)) continue;
                // 在分布式文件系统中获得文件
                DfsFileInfo fileInfo = fastdfsService1.getFile(new MetadataInfo(fsViewConfig.getFsviewSysId()), dfsId);
                if (fileInfo == null) continue;
                byte[] data = fileInfo.getFile();

                String code = jsonObject.getString("code");
                String seqNo = jsonObject.getString("seqNo");
                String deviceId = jsonObject.getString("deviceId");
                String ext = jsonObject.getString("ext");
                String times = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
                //[N_YQ_TES_RPFB]-f8975ec6e2f14e1bb19687ddde4af72b-20160810143425792_2
                String fileName = "["+code+"]-"+deviceId+"-"+times+"_"+seqNo+"."+ext;

                File file =  FileUtil.bytesToFile(data, fileName);
                list.add(file);
            }
            // 压缩文件
            FileUtil.zipFiles(zipFile, list);
            response.setContentType("application/x-download");
            response.addHeader("Content-Disposition", "attachment;filename=" + zipFileName);
            out = response.getOutputStream();
            IOUtils.copy(new FileInputStream(zipFile),out);
            out.flush();
            out.close();
        } catch (Exception e){
            in = null;
            out = null;
        }finally {
            if (in != null){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (out != null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

}
